package com.example.littleken.ormlite_text;

import android.test.InstrumentationTestCase;
import android.util.Log;

import com.example.littleken.ormlite_text.bean.LifeDiary;
import com.example.littleken.ormlite_text.db.DatabaseHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;

import org.junit.Test;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by littleken on 18/6/20.
 */
public class OrmLiteTest extends InstrumentationTestCase {
    //获取数据库帮助类
    private DatabaseHelper getDatabaseHelper() throws SQLException {
        return DatabaseHelper.getInstance(this.getInstrumentation().getTargetContext());
    }
    //获取Dao对象
    private Dao getLifediaryDAO() throws SQLException {
        return getDatabaseHelper().getDao(LifeDiary.class);
    }


    /**
     * 测试插入
     * @throws Exception
     */
    public void testInsert() throws Exception{
        LifeDiary lifeDiary = new LifeDiary("maimai","maimai",getNowTime());
        Dao<LifeDiary,Integer> lifediaryDAO = getLifediaryDAO();
        lifediaryDAO.create(lifeDiary);
    }
    @Test
    public void text(){
        Date time = Calendar.getInstance().getTime();
        Log.e("TAG", String.valueOf(time));
    }

    /**
     * 测试查询
     * @throws Exception
     */
    public void testQueryAll() throws Exception{
        Dao<LifeDiary,Integer> lifediaryDAO = getLifediaryDAO();
        List<LifeDiary> lifeDiaries = lifediaryDAO.queryForAll();
        for(LifeDiary lifeDiary : lifeDiaries){
            Log.i("TAG", lifeDiary.toString());
        }
    }

    public void testUpdate() throws SQLException {
        Dao  lifediaryDAO= getLifediaryDAO();
        UpdateBuilder update = lifediaryDAO.updateBuilder();
        update.setWhere(update.where().eq("id",1));
        update.updateColumnValue("title","内容3");
        update.update();
    }

    public void testDelete() throws SQLException {
        Dao  lifediaryDAO= getLifediaryDAO();
        DeleteBuilder del = lifediaryDAO.deleteBuilder();
        lifediaryDAO.deleteById(9);
    }

    public void testDeleteMore(LifeDiary...lifeDiaries) throws SQLException {
        Dao lifediaryDAO= getLifediaryDAO();
        DeleteBuilder del = lifediaryDAO.deleteBuilder();
        for(int i=0;i<lifeDiaries.length;i++){
            lifediaryDAO.deleteById(lifeDiaries[i].getId());
        }
    }


    public String getNowTime(){
        String time = String.valueOf(Calendar.getInstance().getTime().getTime());
        return time;
    }

}
